<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;

use mbilling\BillingBundle\Model\BonusesModel;
use mbilling\BillingBundle\Model\BonusesTableModel;
use mbilling\BillingBundle\Model\UsersAdminLogsModel;
use mbilling\BillingBundle\Entity\bonuses;
use mbilling\BillingBundle\Entity\usersAdminLogs;

use mbilling\BillingBundle\Form\BonusesForm;

class BonusesController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bonus_model = new BonusesModel($em);
        $bonuses = $bonus_model->findAll();

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Bonuses:user_index.html.twig', array('bonuses' => $bonuses));
            else
                return $this->render('BillingBundle:Bonuses:admin_index.html.twig', array('bonuses' => $bonuses));
        }
        else
            return $this->render('BillingBundle:Bonuses:user_index.html.twig', array('bonuses' => $bonuses));
    }
    public function addAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bonus_model = new BonusesModel($em);
        $bonus = new bonuses();
        $bonus->setCouponNum('0');
        //$bonus_model->create($bonus>initDefaultEntity());
        //return new RedirectResponse($this->generateUrl('bonuses_show'));

        $dir=opendir(dirName('../'.basename(__FILE__)).'/vendor/mpanel/classes/Bonuses/');
        $file_string = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $expl=explode('.', $file);
            $expl_size=sizeof($expl);
            if (mb_strtolower($expl[$expl_size-1],'UTF-8') != 'php')
                continue;
            $file_len = sizeof($file_string);
            $file_string[$file_len] = $file;
        }
        closedir($dir);
        array_multisort($file_string);
        $names = array();
        $coupon_string = array();
        array_push($coupon_string, 'без купона');
        foreach($file_string as $coupon)
        {
            $expl=explode('.', $coupon);
            $class_name = $expl['0'];
            $class_name = 'Bonuses_'.$class_name;
            $check_domain = $this->get('check_domain');
            $class = $class_name::newInstance(NULL, NULL, NULL, $check_domain, $em);
            array_push($names, $class_name);
            array_push($coupon_string, $class->getTitle());
        }
        
        $form = $this->createForm(new BonusesForm($coupon_string), $bonus);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $selected = $form['coupon']->getData();
                if ($selected != 0)
                    $bonus->setCoupon($names[$form['coupon']->getData() - 1]);
                else
                {
                    $bonus->setCoupon('no');
                    $bonus->setCouponNum('0');
                }
                $bonus_model->create($form->getData());

                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();
                $log_model = new UsersAdminLogsModel($em);
                $log = new usersAdminLogs();
                $log->setAdminId($userCurrent->getId());
                $log->setPageId('15');//страница бонусы
                $log->setObjectId($bonus->getId());//изменяемый объект
                $log->setActionTypeId('1');//создание бонуса
                $log_model->create($log);
                return new RedirectResponse($this->generateUrl('bonuses_show'));
            }
        }
        return $this->render('BillingBundle:Bonuses:create.html.twig', array('form' => $form->createView()));
    }
    public function updateAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bonus_model = new BonusesModel($em);
        $bonus = $bonus_model->findByPK($id);

        $dir=opendir(dirName('../'.basename(__FILE__)).'/vendor/mpanel/classes/Bonuses/');
        $file_string = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $expl=explode('.', $file);
            $expl_size=sizeof($expl);
            if (mb_strtolower($expl[$expl_size-1],'UTF-8') != 'php')
                continue;
            $file_len = sizeof($file_string);
            $file_string[$file_len] = $file;
        }
        closedir($dir);
        array_multisort($file_string);
        $names = array();
        $coupon_string = array();
        array_push($coupon_string, 'без купона');
        foreach($file_string as $coupon)
        {
            $expl=explode('.', $coupon);
            $class_name = $expl['0'];
            $class_name = 'Bonuses_'.$class_name;
            $check_domain = $this->get('check_domain');
            $class = $class_name::newInstance(NULL, NULL, NULL, $check_domain, $em);
            array_push($names, $class_name);
            array_push($coupon_string, $class->getTitle());
        }

        $form = $this->createForm(new BonusesForm($coupon_string), $bonus);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $selected = $form['coupon']->getData();
                if ($selected != 0)
                    $bonus->setCoupon($names[$form['coupon']->getData() - 1]);
                else
                    $bonus->setCoupon('no');
                $bonus_model->create($form->getData());

                $securityContext = $this->container->get('security.context');
                $userCurrent = $securityContext->getToken()->getUser();
                $log_model = new UsersAdminLogsModel($em);
                $log = new usersAdminLogs();
                $log->setAdminId($userCurrent->getId());
                $log->setPageId('15');//страница бонусы
                $log->setObjectId($bonus->getId());//изменяемый объект
                $log->setActionTypeId('2');//изменение бонуса
                $log_model->create($log);

                return new RedirectResponse($this->generateUrl('bonuses_show'));
            }
        }
        return $this->render('BillingBundle:Bonuses:create.html.twig', array('form' => $form->createView()));
    }
    public function removeAction($id)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $bonus_model = new BonusesModel($em);
        $bonusTable_model = new BonusesTableModel($em);

        if ($bonusTable_model->checkByPK($id))
            return $this->render('BillingBundle:Bonuses:error.html.twig', array('errors' => array(array('message' => 'Невозможно удалить, удалите сначала зависимые выданные бонусы', 'link' => 'bonuses_table_show'))));

        $bonus = $bonus_model->findByPK($id);
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $bonus_model->removeByPK($id);

        $log_model = new UsersAdminLogsModel($em);
        $log = new usersAdminLogs();
        $log->setAdminId($userCurrent->getId());
        $log->setPageId('15');//страница бонусы
        $log->setObjectId($id);//изменяемый объект
        $log->setActionTypeId('3');//удаление бонуса
        $log_model->create($log);

        return new RedirectResponse($this->generateUrl('bonuses_show'));
    }
}